package com.ebelter.seneo.utils;


import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.SpecialText;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.R;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.models.SeneoNet;
import com.ebelter.seneo.ui.fragments.infos.Info_Weight_Fragment;
import com.ebelter.seneo.ui.fragments.main.Dash_Fragment;
import com.ebelter.seneo.ui.fragments.main.Goal_Fragment;
import com.ebelter.seneo.ui.fragments.main.Info_Fragment;
import com.ebelter.seneo.ui.fragments.main.Set_Fragment;
import com.ebelter.seneo.ui.fragments.main.Trend_Fragment;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Response;

public class SeneoUtils {


    public static final String TAG = "SeneoUtils";

    //发送一个CommonEventBus指令出去
    public static void sendCommonEventBus(String from, String whichReceive, int cmd, String msg){
        CommonEventBus commonEventBus=new CommonEventBus(from,whichReceive,cmd,msg);
        EventBus.getDefault().post(commonEventBus);
    }

    public static void updateCurrentInfoDiaplay(String from){
        SeneoUtils.sendCommonEventBus(from,
                Goal_Fragment.TAG+
                        Info_Fragment.TAG+ Dash_Fragment.TAG+ Trend_Fragment.TAG+ Set_Fragment.TAG
                + Info_Weight_Fragment.TAG,
                IUserContant.ICMDS.UPDATE_CURRENT_USER_INFO,"更新当前用户信息");
    }



    //0代表kg 1代表lb
    public static int getUnitModel(){
        return UserSpUtil.readInt(IUserContant.IUser.userUnitModel);
    }
    //0代表kg 1代表lb
    public static void setUnitModel(int unit){
        UserSpUtil.writeInt(IUserContant.IUser.userUnitModel,unit);
    }




    //获取绑定的地址
    public static String getBondAddress(){
        return UserSpUtil.readString(IUserContant.IUser.bondAddress);
    }

    //获取绑定的名字
    public static String getBondName(){
        return UserSpUtil.readString(IUserContant.IUser.bondName);
    }






    /**
     *
     * @param timeStr 1970-01-01 08:00:00 时间格式永远是这样的
     * @param fatmat 1年月日 2时分  3年月日 时分
     */
    public static String timeFatmat(String timeStr, int fatmat){
        if (TextUtils.isEmpty(timeStr)){
            return "";
        }
        if (timeStr.length()==10){
            //说明时间可能是1970-01-01
            timeStr=timeStr+" 00:00:00";
        }
        String result="";
        if (timeStr.length()!=19){
           
            return result;//说明传进来的时间格式是不正确的
        }
        //String string="1994-16-18 18:19:32";
        int year= NumUtils.string2Int(timeStr.substring(0,4));
        int month=NumUtils.string2Int(timeStr.substring(5,7));
        int day=NumUtils.string2Int(timeStr.substring(8,10));
        int h=NumUtils.string2Int(timeStr.substring(11,13));
        int m=NumUtils.string2Int(timeStr.substring(14,16));
        int s=NumUtils.string2Int(timeStr.substring(17,19));
        if (fatmat==1){
            result = SpecialText.formatDateStampString1(new Date(year-1900,month-1,day,h,m,s).getTime());
        }else if (fatmat==2){
            result=SpecialText.formatDateStampString2(new Date(year-1900,month-1,day,h,m,s).getTime());
        }else if (fatmat==3){
            result=SpecialText.formatDateStampString3(new Date(year-1900,month-1,day,h,m,s).getTime());
        }else if (fatmat==0){
            result = SpecialText.formatDateStampString0(new Date(year-1900,month-1,day,h,m,s).getTime());
        }
        return result;
    }

    //2018-16
    public static String intNumFatmat7(String days) {
        if (TextUtils.isEmpty(days)||days.length()!=7){
            return "";
        }
        int num=NumUtils.string2Int(days.substring(5,7));
        return SpecialText.numberLocle_i(CommonLib.APPContext,num);
    }

    public static String monthFatmat(String days) {
        if (TextUtils.isEmpty(days)||days.length()!=7){
            LogUtils.i(TAG,"格式化月出现错误数据--"+days);
            return "";
        }
        int num=NumUtils.string2Int(days.substring(5,7));
        if (num<=0){
            LogUtils.i(TAG,"格式化月出现错误数据--"+days);
            return "";

        }
        String[] monthTexts = CommonLib.APPContext.getResources().getStringArray(R.array.months);
        if (num>12){
            num=12;
            LogUtils.i(TAG,"格式化月出现错误数据--"+days);
        }
        return monthTexts[num-1];
    }


    public static float setDisplayValue(TextView textView,float kgValue,int unit){
        if (textView==null) return 0;
        float v=adapterDataFloat(kgValue,unit);
        v=NumUtils.numBaoLiuWei1(v);
        textView.setText(v+"");
        return v;
    }



    //unit 0kg 1lb
    public static float adapterDataFloat(float kgValue,int unit){
        if (unit==1){
            return kg2lb(kgValue);
        }
        return kgValue;
    }

    //kg转磅
    public static float kg2lb(float kg){
        //TextUtils.equals("Body Fat-B2", "Body Fat-B2")
            float result = (float) (kg*2.2046);
             result =NumUtils.numBaoLiuWeiDown1(result);
            //这里特别注意的是不是四舍五入 是向下取
            return result;


//        if (TextUtils.equals("Body Fat-B16", "Body Fat-B16")){
//            float dis = (float) (kg*2.20458984375);
//            dis=NumUtils.numBaoLiuWei1( dis);
//            float res = numBaoLiuWei6(dis);//四舍五入 6位
//
//            int i= (int) (res*10);
//            if (i%2!=0){
//                res= (float) (res+0.1);
//            }
//            return res;
//        }
//
//        return (float) (kg * 144480.0/65536.0);
    }

    //磅转kg
    public static float lb2kg(float lb){
        return (float) (lb * 65536.0/144480.0);
    }

    private static float numBaoLiuWei6(float value) {
        float num=(float)((Math.round(value*1000000))/1000000.0);;//如果要求精确4位就*10000然后/10000
        return num;
    }


    //位置是否取反的适配方法
    public static String unitDisplay2(String value,String unit){
        String local = AppUtils.getLocalStr();
        String result;
        if (TextUtils.equals(local,AppUtils.iw)){
            result =  unit+value;
            //是要取反的
            return result;
        }else {
            //不需要取反的
            result = value+unit;
            return result;
        }
    }



    public static int getBirthdayIntValue(String string,int index,int defaultValue){
        if (TextUtils.isEmpty(string)){
            return defaultValue;
        }
        String[] args = string.split("-");
        if (args.length!=3){
            return defaultValue;
        }
        return NumUtils.string2Int(args[index],defaultValue);
    }

    public static int getAgeByBirthday(int year){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR)-year;
    }

    public static String userid2btid(long user_id){
        if (user_id<0){
            user_id=0;
        }
        String userid=user_id+"";
        if (userid.length()>14){
            userid=userid.substring(userid.length()-14,userid.length());
        }
        return userid;
    }


    public static void setTvLevel1(TextView tv,int level){
        //level 0栏 1绿 2黄 3红
        if (tv==null)return;
        if (level==0){
            tv.setTextColor(CommonLib.APPContext.getResources().getColor(R.color.blue));
            tv.setBackgroundResource(R.drawable.sp_blue);
        }else if (level==1){
            tv.setTextColor(CommonLib.APPContext.getResources().getColor(R.color.green));
            tv.setBackgroundResource(R.drawable.sp_green);
        }else if (level==2){
            tv.setTextColor(CommonLib.APPContext.getResources().getColor(R.color.yellow));
            tv.setBackgroundResource(R.drawable.sp_yellow);
        }else if (level==3){
            tv.setTextColor(CommonLib.APPContext.getResources().getColor(R.color.red));
            tv.setBackgroundResource(R.drawable.sp_red);
        }
    }

    public static void setTvLevel2(TextView tv,int level){
        //level 0蓝 1绿 2黄 3红
        if (tv==null)return;
        tv.setTextColor(CommonLib.APPContext.getResources().getColor(R.color.white));

        if (level==0){
            tv.setBackgroundResource(R.drawable.sp_blue4);
        }else if (level==1){
            tv.setBackgroundResource(R.drawable.sp_green2);
        }else if (level==3){
            tv.setBackgroundResource(R.drawable.sp_yellow2);
        }else if (level==4){
            tv.setBackgroundResource(R.drawable.sp_red2);
        }
    }


    public static long getCurrentUserUseId(){
        return UserSpUtil.readLong(IUserContant.IUser.CurrentUserUseId);
    }

    public static void setCurrentUserUseId(long userid){
        UserSpUtil.writeLong(IUserContant.IUser.CurrentUserUseId,userid);
    }

    //根据身高返回建议体重的最小值 height是cm 返回的是kg
    public static float getIdeaWeightMin(int height){
        return (float) (height * height * 0.0001 * 18.5);
    }
    //根据身高返回建议体重的最大值 height是cm 返回的是kg
    public static float getIdeaWeightMax(int height){
        return (float) (height * height * 0.0001 * 24.0);
    }


    //检测小于18岁的数据只能测量体重
    public static ScaleMeasureResult checkScaleMeasureResult18old(ScaleMeasureResult result){
        if (result==null)return null;
        //LogUtils.i(TAG,result.toString());
        if (result.getAge()<18){
            float tempValue=0;
            result.setVisceralFat(tempValue);
            result.setBodyAge(tempValue);
            result.setBodyScore(tempValue);
            result.setSkeletalMuscle(tempValue);
            result.setBmr(tempValue);
            result.setMuscleVolume(tempValue);
            result.setBoneVolume(tempValue);
            result.setProtein(tempValue);
            result.setFat(tempValue);
            result.setWaterRate(tempValue);
        }
        result.setVisceralFat(revisedData(result.getVisceralFat()));
        result.setBodyAge(revisedData(result.getBodyAge()));
        result.setBodyScore(revisedData(result.getBodyScore()));
        result.setSkeletalMuscle(revisedData(result.getSkeletalMuscle()));
        result.setBmr(revisedData(result.getBmr()));
        result.setMuscleVolume(revisedData(result.getMuscleVolume()));
        result.setBoneVolume(revisedData(result.getBoneVolume()));
        result.setProtein(revisedData(result.getProtein()));
        result.setFat(revisedData(result.getFat()));
        result.setWaterRate(revisedData(result.getWaterRate()));

        return result;
    }

    private static float revisedData(float value){
        if (value<0){
            value=0;
        }
        return value;
    }


    //-1隐藏掉 0偏低 1正常 2偏高 3危险
    public static void setLabelLevel(TextView textView,int level){
        if (level<0){
            ViewUtils.hideView(textView);
            return;
        }else{
            ViewUtils.displayView(textView);
        }
        if (level==0){
            ViewUtils.setTextViewStr(textView,R.string.piandi);
            ViewUtils.setBgResource(textView,R.drawable.sp_blue);
            ViewUtils.setTextColor(textView,blueColor);
        }else if (level==1){
            ViewUtils.setTextViewStr(textView,R.string.baiozhun);
            ViewUtils.setBgResource(textView,R.drawable.sp_green);
            ViewUtils.setTextColor(textView,greenColor);
        }else if (level==2){
            ViewUtils.setTextViewStr(textView,R.string.piangao);
            ViewUtils.setBgResource(textView,R.drawable.sp_yellow);
            ViewUtils.setTextColor(textView,yellowColor);
        }else if (level==3){
            ViewUtils.setTextViewStr(textView,R.string.chaozhong);
            ViewUtils.setBgResource(textView,R.drawable.sp_red);
            ViewUtils.setTextColor(textView,redColor);
        }
    }

    //-1隐藏掉 0偏低 1正常 2偏高 3危险
    public static void setLabelLevelRes(ImageView imageView, int level){
        if (level<0){
            ViewUtils.hideView(imageView);
            return;
        }else{
            ViewUtils.displayView(imageView);
        }
        if (level==0){
            ViewUtils.setImageResource(imageView,R.drawable.ic_arrow_down_green);
        }else if (level==1){
            ViewUtils.setImageResource(imageView,0);
        }else if (level==2){
            ViewUtils.setImageResource(imageView,R.drawable.ic_arrow_up_yellow);
        }else if (level==3){
            ViewUtils.setImageResource(imageView,R.drawable.ic_arrow_up_red);
        }
    }

    //0健康 1警戒 2偏高 3危险
    public static void setLabelLevelRes3(ImageView imageView, int level){
        if (level<0){
            ViewUtils.hideView(imageView);
            return;
        }else{
            ViewUtils.displayView(imageView);
        }
        if (level==0){
            ViewUtils.setImageResource(imageView,0);
        }else if (level==1){
            ViewUtils.setImageResource(imageView,R.drawable.ic_arrow_up_yellow);
        }else if (level==2){
            ViewUtils.setImageResource(imageView,R.drawable.ic_arrow_up_yellow);
        }else if (level==3){
            ViewUtils.setImageResource(imageView,R.drawable.ic_arrow_up_red);
        }
    }


    private static final int blueColor = CommonLib.APPContext.getResources().getColor(R.color.blue);
    private static final int greenColor = CommonLib.APPContext.getResources().getColor(R.color.green);
    private static final int yellowColor = CommonLib.APPContext.getResources().getColor(R.color.yellow);
    private static final int redColor = CommonLib.APPContext.getResources().getColor(R.color.red);
    private static final int shuiColor = CommonLib.APPContext.getResources().getColor(R.color.shui);


    //-1隐藏掉 0偏低 1正常 2偏高 3超重
    public static void setLabelLevel2(TextView textView,int level){
        if (level<0){
            ViewUtils.goneView(textView);
            return;
        }else{
            ViewUtils.displayView(textView);
        }

        if (level==0){
            ViewUtils.setTextViewStr(textView,R.string.piandi);
            ViewUtils.setBgResource(textView,R.drawable.sp_blue4);
        }else if (level==1){
            ViewUtils.setTextViewStr(textView,R.string.baiozhun);
            ViewUtils.setBgResource(textView,R.drawable.sp_green2);
        }else if (level==2){
            ViewUtils.setTextViewStr(textView,R.string.piangao);
            ViewUtils.setBgResource(textView,R.drawable.sp_yellow2);
        }else if (level==3){
            ViewUtils.setTextViewStr(textView,R.string.chaozhong);
            ViewUtils.setBgResource(textView,R.drawable.sp_red2);
        }
    }



    //-1隐藏掉 0正常 1警戒 2偏高 3危险
    public static void setLabelLevel3(TextView textView,int level){
        if (level<0){
            ViewUtils.hideView(textView);
            return;
        }else{
            ViewUtils.displayView(textView);
        }
        if (level==0){
            ViewUtils.setTextViewStr(textView,R.string.baiozhun);
            ViewUtils.setBgResource(textView,R.drawable.sp_green);
            ViewUtils.setTextColor(textView,greenColor);
        }else if (level==1){
            ViewUtils.setTextViewStr(textView,R.string.jingjie);
            ViewUtils.setBgResource(textView,R.drawable.sp_blue);
            ViewUtils.setTextColor(textView,blueColor);
        }else if (level==2){
            ViewUtils.setTextViewStr(textView,R.string.piangao);
            ViewUtils.setBgResource(textView,R.drawable.sp_yellow);
            ViewUtils.setTextColor(textView,yellowColor);
        }else if (level==3){
            ViewUtils.setTextViewStr(textView,R.string.weixian);
            ViewUtils.setBgResource(textView,R.drawable.sp_red);
            ViewUtils.setTextColor(textView,redColor);
        }
    }



    //-1隐藏掉 0偏低 1标准 2偏胖 3肥胖
    public static void setLabelLevel41(TextView textView,int level){
        if (level<0){
            ViewUtils.hideView(textView);
            return;
        }else{
            ViewUtils.displayView(textView);
        }

        LogUtils.i(TAG,"------textView.getTextSize()="+textView.getTextSize());
        textView.setTextSize(14);
        if (level==0){
            ViewUtils.setTextViewStr(textView,R.string.piandi);
            ViewUtils.setBgResource(textView,R.drawable.sp_blue);
            ViewUtils.setTextColor(textView,blueColor);
        }else if (level==1){
            ViewUtils.setTextViewStr(textView,R.string.baiozhun);
            ViewUtils.setBgResource(textView,R.drawable.sp_green);
            ViewUtils.setTextColor(textView,greenColor);
        }else if (level==2){
            ViewUtils.setTextViewStr(textView,R.string.pianpang);
            textView.setTextSize(11);
            ViewUtils.setBgResource(textView,R.drawable.sp_yellow);
            ViewUtils.setTextColor(textView,yellowColor);
        }else if (level==3){
            ViewUtils.setTextViewStr(textView,R.string.feipang);
            ViewUtils.setBgResource(textView,R.drawable.sp_red);
            ViewUtils.setTextColor(textView,redColor);
        }
    }



    //-1隐藏掉 0缺水 1良好
    public static void setLabelLevel51(TextView textView,int level){
        if (level<0){
            ViewUtils.hideView(textView);
            return;
        }else{
            ViewUtils.displayView(textView);
        }
        if (level==0){
            ViewUtils.setTextViewStr(textView,R.string.queshui);
            ViewUtils.setBgResource(textView,R.drawable.sp_red);
            ViewUtils.setTextColor(textView,redColor);
        }else if (level==1){
            ViewUtils.setTextViewStr(textView,R.string.biaozhun);
            ViewUtils.setBgResource(textView,R.drawable.sp_green);
            ViewUtils.setTextColor(textView,greenColor);
        }else if (level==2){
            ViewUtils.setTextViewStr(textView,R.string.lianghao);
            ViewUtils.setBgResource(textView,R.drawable.sp_shui);
            ViewUtils.setTextColor(textView,shuiColor);
        }
    }




    public static boolean getGoogleFitOpenFlag(){
        return UserSpUtil.readBoolean(IUserContant.IUser.GoogleFitOpenFlag,false);
    }
    public static void setGoogleFitOpenFlag(boolean openFlag){
        UserSpUtil.writeBoolean(IUserContant.IUser.GoogleFitOpenFlag,openFlag);
    }


    public static String getFitbitToken(){
        return UserSpUtil.readString(IUserContant.IUser.FitBitToken,null);
    }
    public static void setFitbitToken(String token){
        UserSpUtil.writeString(IUserContant.IUser.FitBitToken,token);
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        if (activity==null||editText==null)return;
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(editText, 0);
        }
    }







    public static void uploadWeight2Fitbit(float weight,float fat,String measureTime){



        String data = measureTime.substring(0,10);
        String time = measureTime.substring(11);
        LogUtils.i(TAG,"uploadWeight2Fitbit准备上传测量数据到Fitbitapp weight="+weight+"--fat="+fat+"--data="+data+"--time="+time);
        if (!NetUtils.available()){
            LogUtils.i(TAG,"uploadWeight2Fitbit网络不可用reture");
            return;
        }
        String access_token=SeneoUtils.getFitbitToken();
        if (TextUtils.isEmpty(access_token)){
            LogUtils.i(TAG,"uploadWeight2Fitbit---access_token为空--reture");
            return;
        }


        String url="https://api.fitbit.com/1/user/-/body/log/weight.json";
        String url2="https://api.fitbit.com/1/user/-/body/log/fat.json";

        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization","Bearer "+access_token);

        HttpParams httpParams = new HttpParams();
        httpParams.put("weight",weight);
        httpParams.put("date",data);
        httpParams.put("time",time);

        HttpParams httpParams2 = new HttpParams();
        httpParams2.put("fat",fat);
        httpParams2.put("date",data);
        httpParams2.put("time",time);


        SeneoNet.getIntance().post2(TAG, url, headers, httpParams,new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.i(TAG, "---上传体重到fitbit --onSuccess-- s = " + s);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.i(TAG, "---上传体重到fitbit ---onError- " +e.toString());
                e.printStackTrace();
            }
        });

        SeneoNet.getIntance().post2(TAG, url2, headers, httpParams2,new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.i(TAG, "---上传体脂到fitbit --onSuccess-- s = " + s);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.i(TAG, "---上传体脂到fitbit ---onError- " +e.toString());
                e.printStackTrace();
            }
        });
    }







}
